﻿namespace Stopwatch.Storage
{
    using System.IO.IsolatedStorage;
    using System.Runtime.Serialization.Json;

    internal class IsolatedStorage : IStorage
    {
        public void Write<T>(string key, T obj) where T : class
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream stream = file.CreateFile(key))
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                ser.WriteObject(stream, obj);
            }
        }

        public T Read<T>(string key) where T : class
        {
            T t = null;
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream stream = file.OpenFile(key, System.IO.FileMode.OpenOrCreate))
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                t = ser.ReadObject(stream) as T;
            }

            return t;
        }

        public void Delete(string key)
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            if (file.FileExists(key))
            {
                file.DeleteFile(key);
            }
        }

        public bool Exists(string key)
        {
            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            return file.FileExists(key);
        }
    }
}
